package a07_二叉树;

/**
 * <p>
 * a12_平衡二叉树复习0
 * </p>
 *
 * @author flyduck
 * @since 2024-12-29
 */
public class a12_平衡二叉树复习0 {
    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode(1,
                new TreeNode(2,
                        new TreeNode(3,
                                new TreeNode(4),
                                new TreeNode(4)),
                        new TreeNode(3)),
                new TreeNode(2));
        a12_平衡二叉树复习0 test = new a12_平衡二叉树复习0();
        boolean balanced = test.isBalanced(treeNode);
        System.out.println("balanced = " + balanced);
    }


    public boolean isBalanced(TreeNode root) {
        return getHeight(root) != -1;
    }

    public int getHeight(TreeNode root){
        if (root == null) {
            return 0;
        }
        int leftHeight = getHeight(root.left);
        if (leftHeight == -1) {
            return -1;
        }
        int rightHeight = getHeight(root.right);
        if (rightHeight == -1) {
            return -1;
        }

        if (Math.abs(leftHeight - rightHeight) > 1) {
            return -1;
        }else {
            return Math.max(leftHeight, rightHeight) + 1;
        }
    }
}
